<?php
/**
 * This file is part of the Agora distribution. 
 * Detailed copyright and licensing information can be found
 * in the gpl-3.0.txt file which should be included in the distribution.
 * 
 * @version		$Id: 3.0.14 Olympus 2010-09-28 rammstein4o $
 * @copyright  2007 - 2010 jVitals
 * @license   GPLv3 Open Source
 * @link       http://jvitals.com
 * @since      File available since initial release
 */
	defined ('IN_AGORA') or die;

	class TaskController extends AgoraPostController
	{
		function _default()
		{
            $mode = Agora::getVar('mode');                        
            if ( strpos($_SERVER['PHP_SELF'],'index2.php')!=0 ) $mode='agroup';
		    
			$forum_model = & Model::getInstance('ForumModel');
			$this->authenticate($this->id,'post_topic');

			$forum = $forum_model->load($this->id);
			if ($forum['single_topic']) {  // Check for Single Topic forums
				if ($forum_model->hasTopic($forum['id'], $this->agora_user['username'] )) {//User has started a topic, cant start another so we Close to him.
					$this->view->template = 'post/max_met';
					return;
				}
			}
			
			$session_username = Agora::getSessionVar('topic_username');
			$session_email = Agora::getSessionVar('guest_email');
			Agora::setSessionVar('topic_username', '');
			Agora::setSessionVar('guest_email', '');
			/*
			$topic_username = Agora::getPostVar('topic_username',$session_username);
			$topic_username = empty($topic_username) ? $this->agora_user['username'] : $topic_username;
			$topic_email = Agora::getPostVar('guest_email',$session_email);
			$topic_email = empty($topic_email) ? false : $topic_email;
			*/
			$topic_username = empty($session_username) ? $this->agora_user['username'] : $session_username;
			$topic_email = empty($session_email) ? false : $session_email;
			$this->view->assign('topic_username',$topic_username);
			$this->view->assign('topic_email',$topic_email);
			
            $subject = Agora::getSessionVar('subject');
            $message = Agora::getSessionVar('message');
            $desc = Agora::getSessionVar('desc');
			Agora::setSessionVar('subject', '');
			Agora::setSessionVar('message', '');
			Agora::setSessionVar('desc', '');
			
			$this->view->assign('forum',$forum);

			$catnav_helper = & $this->helper('catnav');
			$catnav_helper->fromForum($this->id);
			
			// trigger before display event
			JPluginHelper::importPlugin('agora');
			$dispatcher =& JDispatcher::getInstance();
			$plugin_template =  $dispatcher->trigger('onTopicCreateForm', array(&$forum, false));
			$this->view->assign('plugin_template', implode("<br />\n", $plugin_template));

			$access_helper = & $this->helper('access');
			$access = $access_helper->getForumAccess($this->id);
			$this->view->assign('access',$access);

			$icons_model = & Model::getInstance('TopicIconsModel');
			$this->view->assign('cur_forum_id',intval($this->id));
			$this->view->assign('topic_icons',$icons_model->loadAll());
			$this->view->assign('subject',$subject);
			$this->view->assign('desc',$desc);
            $this->view->assign('post_body',$message);
			
			if ($this->agora_user['is_guest']) {
				$banned = false;
			} else {
				$ban_model = & Model::getInstance('BanModel');
				$banned = $ban_model->isBanned($this->agora_user['username']);
			}
			$this->view->assign('user_banned',$banned);
			
			//$twitter_url = Agora::getUrlContent('http://is.gd/api.php?longurl=' . Agora::getSelf()); //TODO JOPPORT УБРАТЬ КОММЕНТАРИЙ!!! закомментировал, т.к. на работе блокируется работа из-за этого
			if ($twitter_url !== false) {
				$this->view->assign('twitter_url', $twitter_url);
				$this->view->assign('show_twitter', true);
			} else {
				$this->view->assign('show_twitter', false);
			}
			
            if ('agroup' == $mode)
            $this->view->template = 'post/topic_agroup';
            else
            $this->view->template = 'post/topic';
			
		}

		function save() {
			
            $mode = Agora::getVar('mode');                        
            if (strpos($_SERVER['PHP_SELF'],'index2.php') != 0) $mode='agroup';
		    
			$this->authenticate($this->id,'post_topic');

			$forum_model = & Model::getInstance('ForumModel');
			$topic_model = & Model::getInstance('TopicModel');
			$post_model = & Model::getInstance('PostModel');
			$parser = $this->helper('parser');
			
			$forum = $forum_model->load($this->id);
			$approved = ($this->agora_user['is_superadmin'] || $this->agora_user['is_admin'] || $this->agora_user['is_moderator']) ? 1 : !(int)$forum['use_moderation'];

			if (!$this->agora_user['is_superadmin'] &&
				$this->access_model->authenticate($this->agora_user['id'],$forum['id'],'use_captcha')) {
				$captcha = Agora::getPostVar('captcha');
				$c_key = Agora::getSessionVar('captcha');

				if (trim($captcha) !== trim($c_key) || !$captcha) {
					Agora::showMessage(Agora::lang('Bad captcha'));
					Agora::setSessionVar('subject', Agora::getPostVar('subject','') );
					Agora::setSessionVar('message', Agora::getPostVar('req_message','',true) );
					Agora::setSessionVar('desc', Agora::getPostVar('desc','') );
					Agora::setSessionVar('topic_username', Agora::getPostVar('topic_username','') );
					Agora::setSessionVar('guest_email', Agora::getPostVar('guest_email','') );
					Agora::redirect(Agora::getRefferer());
				}
			}
			
			$subject = Agora::getPostVar('subject','No subject');
			$desc = Agora::getPostVar('desc','');
			$topic_userid = Agora::getPostVar('topic_userid','');
			$topic_username = Agora::getPostVar('topic_username','');
			$topic_username = empty($topic_username) ? $this->agora_user['username'] : $topic_username;
			$topic_email = Agora::getPostVar('guest_email','');
			$topic_email = empty($topic_email) ? false : $topic_email;
			$splitpost = Agora::getPostVar('splitpost','');
			$delete_source_post = Agora::getPostVar('delete_source_post','');
			$message = Agora::getPostVar('req_message','', true);
			$message = $parser->fix_broken_bbcode($message);
			$hide_smilies = Agora::getPostVar('hide_smilies',0);
			$topic_icon = intval(Agora::getPostVar('topic_icon',0));
			
			if ($approved) {
			
				// Trigger onBeforeNewTopic Agora plugin event
				JPluginHelper::importPlugin( 'agora' );
				$dispatcher =& JDispatcher::getInstance();
				$options = new JObject;
				$options->forum_id = $this->id ;
				$options->subject = $subject ;
				$options->desc = $desc ;
				$options->icon = $topic_icon ;
				$options->user_name = ($topic_userid ? $topic_username : $this->agora_user['username'] );
				$options->user_id = ($topic_userid ? $topic_userid : $this->agora_user['id'] );
				$options->message = $message ;
				$options->topic_id = null;
				$plg_result =  $dispatcher->trigger('onBeforeNewTopic', array(&$options)) ;	
			}
			
			// Add new topic and post for it
			if ($topic_userid) {
				$topic_id = $topic_model->add($this->id, $subject, $desc, $topic_icon, $topic_username, $topic_userid, $message, $hide_smilies, $approved, $topic_email);
			} else {
				$topic_id = $topic_model->add($this->id, $subject, $desc, $topic_icon, $topic_username/*$this->agora_user['username']*/, $this->agora_user['id'], $message, $hide_smilies, $approved, $topic_email);
			}
			$topic = $topic_model->load($topic_id);
			
			if ($approved) {
			
				// Trigger onAfterNewTopic Agora plugin event
				$options->topic_id 	= $topic_id;
				$plg_result = $dispatcher->trigger('onAfterNewTopic', array(&$options));
				
				// If AUP plugin exists - add user points
				$api_AUP = JPATH_SITE.DS.'components'.DS.'com_alphauserpoints'.DS.'helper.php';
				if (file_exists($api_AUP))	{
					require_once ($api_AUP);
					AlphaUserPointsHelper::newpoints( 'plgaup_newtopic_agora', '', '', Agora::lang('AUP_TOPIC'));
				}
				
				// Send notification to subscribed users
				$subscription_helper = & $this->helper('subscription');
				$subscription_helper->newPost($topic['last_post_id'], $this->id);
				
			} else {
				Agora::showMessage(Agora::lang('POST_MODERATION_MESSAGE'));
			}
			
			if($delete_source_post) {
			    $post_model->delete($delete_source_post);
			}
			
			if($splitpost) {
				foreach ($splitpost as $post_id) {
					$post = $post_model->load($post_id);
					$topic_model->addPost($topic_id, $this->id, $post['message'], $post['poster_id'], $post['poster'], $post['hide_smilies'], $approved);
					$post_model->delete($post_id);
				}
			}

			$timeout = AGORA_TIME - intval($this->agora_config['o_timeout_visit']) * 86400;
			$topic_model->cleanupRead($timeout);
			
			// Subscribe user to this topic
			if ($subscribe = Agora::getPostVar('subscribe',0)) {
				$subscription_model = & Model::getInstance('SubscriptionModel');
				$subscription_model->add(array('user_id' => $this->agora_user['id'], 'topic_id' => $topic_id));
				Agora::showMessage(Agora::lang('You are now subscribed on topic ') . ' '  . AString::escape($topic['subject']));
			}
			
			// Send notification to mods and admins if the post is moderated
			if (!$approved) {
				$subscription_helper = &$this->helper('subscription');
				$subscription_helper->newPost($topic['last_post_id'], $topic['forum_id'], true);
			}
			
			// Redirect
			if ($approved) {
				if ($mode == 'agroup') {
					Agora::redirect(Agora::makeURL(array('task' => 'topic', 'id' => $topic_id), true, true ));
				} else {
					Agora::redirect(Agora::makeURL(array('task' => 'topic', 'id' => $topic_id)));
				}
			} else {
				Agora::redirect(Agora::makeURL(array('task' => 'forum', 'id' => $topic['forum_id'])));
			}
		}

		function preview() {
			
			$topic_icon = intval(Agora::getPostVar('topic_icon',0));
			$desc = Agora::getPostVar('desc','');
			$subject = Agora::getPostVar('subject','');

			$raw_message = Agora::getPostVar('req_message','', true);
			$message = $raw_message;
			$hide_smilies = Agora::getPostVar('hide_smilies',0);

			$parser = $this->helper('parser');

			$message = $parser->parseMessage($raw_message, $hide_smilies);
			$topic_userid = Agora::getPostVar('topic_userid','');
			$topic_username = Agora::getPostVar('topic_username','');			
			
			$post = array();
			$post = array();
			$signature = '';
			$post['id'] = 0;
            if ($topic_userid)
            {
                $user_model = & Model::getInstance('UserModel');
                $post['user'] = $user_model->load($topic_userid);
			    $post['poster_id'] = $topic_userid;
			    $post['poster'] = $topic_username;
                if ($post['user']['show_sig']) {
				$signature = $parser->parseSignature($post['user']['signature']);
			    }
            }
            else
            {
            	if ($this->agora_user['show_sig']) {
				$signature = $parser->parseSignature($this->agora_user['signature']);
			    }
                $post['user'] = $this->agora_user;
                $post['poster_id'] = $this->agora_user['id'];
			    $post['poster'] = $this->agora_user['username'];    
            }
            

			
			$post['posted'] = time();
			$user_helper = &$this->helper('user');

			$post['user'] = $user_helper->prepareUserAvatar($post['user']);
			$post['user'] = $user_helper->prepareUserTitle($post['user']);

//			$post['id'] = 0;
/*			$post['poster_id'] = $this->agora_user['id'];
			$post['poster'] = $this->agora_user['username'];
			$post['posted'] = time();*/

			$post['message'] = $message;
			$post['user']['signature'] = $signature;

			$topic = array();
			$topic['status'] = 'ag_inew';
			// we don't know id, but we need something for topic_row.tpl
			$topic['id'] = -1;
			$topic['icon_topic'] = $topic_icon;
			$topic['subject'] = $subject;
			$topic['descrip_t'] = $desc;
			
			if ($topic_username)
            {
			    $topic['poster'] = $topic_username;
                $topic['last_poster'] = $topic_username;
            }
            else
            {
                $topic['poster'] = $this->agora_user['username'];
                $topic['last_poster'] = $this->agora_user['username'];
            }
			$topic['sticky'] = 0;
			$topic['new'] = 1;
			$topic['num_views'] = 0;
			$topic['num_replies'] = 0;
			$topic['last_post'] = AGORA_TIME;

			$this->view->assignRef('topic',$topic);

			$this->view->assignRef('post',$post);
			$this->view->assign('access',array());
			$this->view->assign('post_num','-');
			$this->view->assign('topic_id',-1);
			$this->view->assign('post_id',-1);

			$this->view->assign('topic_icon',$topic_icon);
			$this->view->assign('raw_message',$raw_message);
			$this->view->assign('hide_smilies',$hide_smilies);

/*			$this->view->assign('merge',$merge);
			$this->view->assign('subscribe',$subscribe);*/

			$this->view->template = 'post/preview_topic';

			$this->display();
			jexit(0);
		}

		function delete()
		{
			$this->authenticateTopic($this->id,'delete_topics');
			
			$this->view->assign('topic_id',$this->id);
			$this->view->template = 'post/delete_topic';
		}

		function select_forum()
		{
			$this->view->assign('url',Agora::makeURL(array('task'=>'post','page'=>'topic')));
			$this->view->assign('agora_itemid', Agora::getVar('Itemid',''));
			$this->view->template = 'post/select_forum';
		}
	}
